package com.lucenex.core;

import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;

import org.apache.lucene.analysis.miscellaneous.PerFieldAnalyzerWrapper;

import com.ld.ThreadPool.LoggerFactory;
import com.lucenex.bean.BeanConfig;
import com.lucenex.dic.lucene.LDAnalyzer;
import com.lucenex.util.OpenLuceneSource;

/**
 * 核心控制类
 * @author zxw
 *
 */
public class LuceneX implements InitConfig{

	private static LuceneDataSource source;
	
	private static Logger logger = LoggerFactory.getLogger(LuceneX.class);

	/**
	 * 启动器
	 * @param className
	 * @throws InstantiationException
	 * @throws IllegalAccessException
	 * @throws IOException
	 * @throws ClassNotFoundException
	 */
	public static void start(String className) throws InstantiationException, IllegalAccessException, IOException, ClassNotFoundException{
		logger.info("luceneX start--->start");
		Class<?> clas = Class.forName(className);
		start(clas);
		logger.info("luceneX start--->end");
	}
	
	public static void start(Class<?> coreConfig) throws IOException, InstantiationException, IllegalAccessException {
		logger.info("luceneX start--->start");
		source = LuceneDataSource.build();
		CoreConfig newInstance = (CoreConfig) coreConfig.newInstance();
		newInstance.configPlugin(BeanConfig.build());
		//实例化数据源
		newInstance.configLuceneX(new LuceneX());
		//启动自动回收站
		DoShutDownWork.build();
		logger.info("luceneX start--->end");
	}

	/**
	 * 手动提交数据
	 * @throws IOException
	 */
	public static void submit() throws IOException {
		source.submit();
	}

	@Override
	public void add(String indexPath, String dataKey) {
		createSource(indexPath, dataKey, false, null);
	}
	
	@Override
	public void add(String indexPath, String dataKey, boolean highlight) {
		createSource(indexPath, dataKey, highlight, null);
	}

	@Override
	public void add(String indexPath, String dataKey, boolean highlight, PerFieldAnalyzerWrapper analyzer) {
		createSource(indexPath, dataKey, highlight, analyzer);
	}

	@Override
	public void createSource(String indexPath,String dataKey, boolean highlight, PerFieldAnalyzerWrapper analyzer) {
		LuceneXConfig config = new LuceneXConfig();
		config.setIndexPath(indexPath);
		config.setAnalyzer(analyzer == null ? new PerFieldAnalyzerWrapper(new LDAnalyzer(dataKey)):analyzer);
		try {
			
			config.setWriter(OpenLuceneSource.indexWriter(indexPath+dataKey, config.getAnalyzer()));
		} catch (IOException e) {
			logger.log(Level.SEVERE, "luceneX createSource createWriter error", e);
		}
		try {
			config.setSearcher(OpenLuceneSource.dynamicIndexSearcher(config.getWriter()));
		} catch (IOException e) {
			logger.log(Level.SEVERE, "luceneX createSource createSearcher error", e);
		}
		source.setDataSource(dataKey, config);
	}
}
